<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="billing-method-form"
    >
      <!-- 基本信息 -->
      <el-form-item label="计费方式名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入计费方式名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <!-- 费用类型显示 -->
      <el-form-item label="费用类型">
        <el-tag :type="getFeeTypeTagType(props.feeType)" size="large">
          {{ getFeeTypeLabel(props.feeType) }}
        </el-tag>
      </el-form-item>

      <!-- 物业公司显示 -->
      <el-form-item label="物业公司" v-if="props.selectedCompanyName">
        <el-tag type="info" size="large">
          {{ props.selectedCompanyName }}
        </el-tag>
      </el-form-item>

      <el-form-item label="建筑类型" prop="buildingTypeName">
        <el-select
          v-model="form.buildingTypeName"
          placeholder="请选择建筑类型"
          style="width: 100%"
          clearable
          @change="handleBuildingTypeChange"
        >
          <el-option
            v-for="buildingType in buildingTypeList"
            :key="buildingType.id"
            :label="buildingType.buildingTypeName"
            :value="buildingType.buildingTypeName"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="计费类型" prop="type">
        <el-select
          v-model="form.type"
          placeholder="请选择计费类型"
          style="width: 100%"
          @change="handleTypeChange"
        >
          <el-option
            v-for="option in typeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <!-- 动态表单字段 -->
      <template v-if="form.type === 0">
        <!-- 按面积计费 -->
        <el-form-item label="单价" prop="unitPrice">
          <el-input-number
            v-model="form.unitPrice"
            :min="0.01"
            :precision="2"
            :step="0.01"
            placeholder="请输入单价"
            style="width: 100%"
          />
          <span class="unit-text">元/㎡</span>
        </el-form-item>
      </template>

      <template v-else-if="form.type === 1">
        <!-- 固定费用 -->
        <el-form-item label="固定金额" prop="fixedAmount">
          <el-input-number
            v-model="form.fixedAmount"
            :min="0.01"
            :precision="2"
            :step="0.01"
            placeholder="请输入固定金额"
            style="width: 100%"
          />
          <span class="unit-text">元</span>
        </el-form-item>
      </template>

      <template v-else-if="form.type === 2">
        <!-- 阶梯计费 -->
        <el-form-item label="阶梯配置" prop="tierConfig">
          <div class="tier-config">
            <div class="tier-header">
              <span class="tier-title">阶梯计费配置</span>
              <el-button type="primary" size="small" @click="addTier">
                <el-icon><Plus /></el-icon>
                添加阶梯
              </el-button>
            </div>
            <div v-for="(tier, index) in form.tierConfig" :key="index" class="tier-item">
              <div class="tier-header">
                <span class="tier-title">阶梯 {{ index + 1 }}</span>
                <el-button type="danger" size="small" @click="removeTier(index)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
              <el-row :gutter="16">
                <el-col :span="8">
                  <el-form-item :label="`起始${getTierUnitText()}`" :prop="`tierConfig.${index}.start`">
                    <el-input-number
                      v-model="tier.start"
                      :min="0"
                      :precision="2"
                      :step="0.01"
                      placeholder="起始值"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="`结束${getTierUnitText()}`" :prop="`tierConfig.${index}.end`">
                    <el-input-number
                      v-model="tier.end"
                      :min="0"
                      :precision="2"
                      :step="0.01"
                      placeholder="结束值"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单价" :prop="`tierConfig.${index}.price`">
                    <el-input-number
                      v-model="tier.price"
                      :min="0.01"
                      :precision="2"
                      :step="0.01"
                      placeholder="单价"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form-item>
      </template>

      <template v-else-if="form.type === 3">
        <!-- 按表计费 -->
        <el-form-item label="单价" prop="unitPrice">
          <el-input-number
            v-model="form.unitPrice"
            :min="0.01"
            :precision="2"
            :step="0.01"
            placeholder="请输入单价"
            style="width: 100%"
          />
          <span class="unit-text">{{ getUnitText() }}</span>
        </el-form-item>
      </template>

      <template v-else-if="form.type === 4">
        <!-- 阶梯电价 -->
        <el-form-item label="阶梯配置" prop="tierConfig">
          <div class="tier-config">
            <div class="tier-header">
              <span class="tier-title">阶梯电价配置</span>
              <el-button type="primary" size="small" @click="addTier">
                <el-icon><Plus /></el-icon>
                添加阶梯
              </el-button>
            </div>
            <div v-for="(tier, index) in form.tierConfig" :key="index" class="tier-item">
              <div class="tier-header">
                <span class="tier-title">阶梯 {{ index + 1 }}</span>
                <el-button type="danger" size="small" @click="removeTier(index)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
              <el-row :gutter="16">
                <el-col :span="8">
                  <el-form-item :label="`起始${getTierUnitText()}`" :prop="`tierConfig.${index}.start`">
                    <el-input-number
                      v-model="tier.start"
                      :min="0"
                      :precision="2"
                      :step="0.01"
                      placeholder="起始值"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="`结束${getTierUnitText()}`" :prop="`tierConfig.${index}.end`">
                    <el-input-number
                      v-model="tier.end"
                      :min="0"
                      :precision="2"
                      :step="0.01"
                      placeholder="结束值"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="电价" :prop="`tierConfig.${index}.price`">
                    <el-input-number
                      v-model="tier.price"
                      :min="0.01"
                      :precision="2"
                      :step="0.01"
                      placeholder="电价"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form-item>
      </template>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入计费方式描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="排序" prop="sortOrder">
        <el-input-number
          v-model="form.sortOrder"
          :min="0"
          :max="999"
          placeholder="请输入排序值"
          style="width: 100%"
        />
        <span class="help-text">数字越小排序越靠前</span>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { buildingTypeApi } from '../../../api/buildingType'

// Props
interface Props {
  modelValue: boolean
  billingMethod?: any
  feeType?: string
  selectedCompanyId?: number
  selectedCompanyName?: string
}

const props = withDefaults(defineProps<Props>(), {
  feeType: 'property'
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  confirm: [data: any]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const buildingTypeList = ref<any[]>([])

// 表单数据
const form = reactive({
  id: undefined as number | undefined,
  name: '',
  buildingTypeName: undefined as string | undefined,
  type: 0,
  unitPrice: undefined as number | undefined,
  fixedAmount: undefined as number | undefined,
  tierConfig: [] as any[],
  description: '',
  status: 1,
  sortOrder: 1,
  remark: ''
})

// 监听表单数据变化，用于调试
watch(() => form.type, (newVal) => {
  console.log('表单计费类型变化:', newVal, '类型:', typeof newVal)
})

// 监听整个表单数据变化，用于调试
watch(() => form, (newVal) => {
  console.log('表单数据变化:', newVal)
}, { deep: true })

// 计费类型选项
const typeOptions = computed(() => {
  console.log('计算计费类型选项，当前费用类型:', props.feeType)
  
  const options = [
    { label: '按面积计费', value: 0 },
    { label: '固定费用', value: 1 }
  ]
  
  // 物业费支持按面积计费和固定费用
  if (props.feeType === 'property') {
    // 物业费默认只有这两种类型
  } else if (props.feeType === 'gas' || props.feeType === 'electricity') {
    options.push({ label: '阶梯计费', value: 2 })
  } else if (props.feeType === 'water') {
    options.push({ label: '按表计费', value: 3 })
  } else if (props.feeType === 'electricity') {
    options.push({ label: '阶梯电价', value: 4 })
  }
  
  console.log('计费类型选项:', options)
  return options
})

// 对话框标题
const dialogTitle = computed(() => {
  return form.id ? '编辑计费方式' : '新增计费方式'
})

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 获取费用类型标签
const getFeeTypeLabel = (feeType: string) => {
  const feeTypeMap: Record<string, string> = {
    property: '物业费',
    sanitation: '卫生费',
    gas: '燃气费',
    water: '水费',
    electricity: '电费'
  }
  return feeTypeMap[feeType] || feeType
}

// 获取费用类型标签颜色
const getFeeTypeTagType = (feeType: string): 'success' | 'primary' | 'warning' | 'info' | 'danger' => {
  const tagTypeMap: Record<string, 'success' | 'primary' | 'warning' | 'info' | 'danger'> = {
    property: 'primary',
    sanitation: 'success',
    gas: 'warning',
    water: 'info',
    electricity: 'danger'
  }
  return tagTypeMap[feeType] || 'info'
}

// 获取单位文本
const getUnitText = () => {
  const unitMap: Record<string, string> = {
    water: '元/m³',
    gas: '元/m³',
    electricity: '元/kWh',
    property: '元/㎡',
    sanitation: '元'
  }
  return unitMap[props.feeType] || '元/单位'
}

// 获取阶梯单位文本
const getTierUnitText = () => {
  const unitMap: Record<string, string> = {
    gas: 'm³',
    electricity: 'kWh'
  }
  return unitMap[props.feeType] || '单位'
}

// 加载建筑类型列表
const loadBuildingTypeList = async () => {
  if (!props.selectedCompanyId) {
    buildingTypeList.value = []
    return
  }
  
  try {
    // 编辑时使用不分页的接口，新增时也使用不分页接口
    const response = await buildingTypeApi.getBuildingTypesByPropertyCompanyId(props.selectedCompanyId)
    if (response.code === 200) {
      // 处理返回的数据，确保buildingTypeName字段正确
      const records = response.data || []
      buildingTypeList.value = records.map((item: any) => {
        // 确保buildingTypeName是字符串类型
        let buildingTypeName = item.buildingTypeName
        if (Array.isArray(buildingTypeName)) {
          buildingTypeName = buildingTypeName[0] || ''
          console.warn('建筑类型数据中buildingTypeName是数组，取第一个元素:', item.buildingTypeName)
        }
        return {
          ...item,
          buildingTypeName: buildingTypeName || item.categoryName || '未知类型'
        }
      })
      
      // 新增模式下默认选中第一个建筑类型
      if (buildingTypeList.value.length > 0 && !form.id && !form.buildingTypeName) {
        form.buildingTypeName = buildingTypeList.value[0].buildingTypeName
        // 自动生成计费方式名称
        generateBillingMethodName()
      }
    } else {
      ElMessage.error(response.message || '加载建筑类型列表失败')
      buildingTypeList.value = []
    }
  } catch (error) {
    console.error('加载建筑类型列表失败:', error)
    ElMessage.error('加载建筑类型列表失败')
    buildingTypeList.value = []
  }
}

// 自动生成计费方式名称
const generateBillingMethodName = () => {
  // 只有在新增模式下才自动生成名称
  if (form.id) {
    return
  }
  
  // 获取计费类型标签
  const typeOption = typeOptions.value.find(option => option.value === form.type)
  const typeLabel = typeOption ? typeOption.label : ''
  
  // 获取建筑类型名称
  const buildingTypeName = form.buildingTypeName || '通用'
  
  // 生成计费方式名称：建筑类型名 + '_计费方式'
  form.name = `${buildingTypeName}_计费方式`
}

// 处理建筑类型变化
const handleBuildingTypeChange = (value: string) => {
  console.log('选中的建筑类型:', value)
  // 当建筑类型变化时，也自动生成计费方式名称
  generateBillingMethodName()
}

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入计费方式名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  buildingTypeName: [
    { required: true, message: '请选择建筑类型', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择计费类型', trigger: 'change' },
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
          callback(new Error('请选择计费类型'))
        } else if (typeof value !== 'number' || isNaN(value)) {
          callback(new Error('计费类型必须是数字'))
        } else if (value < 0 || value > 4) {
          callback(new Error('计费类型值无效'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  unitPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '单价必须大于0', trigger: 'blur' }
  ],
  fixedAmount: [
    { required: true, message: '请输入固定金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '固定金额必须大于0', trigger: 'blur' }
  ],
  sortOrder: [
    { type: 'number', min: 0, message: '排序值不能小于0', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ],
  remark: [
    { max: 500, message: '备注不能超过500个字符', trigger: 'blur' }
  ]
}

// 方法
const handleTypeChange = () => {
  // 重置相关字段
  form.unitPrice = undefined
  form.fixedAmount = undefined
  form.tierConfig = []
  
  // 根据类型设置默认值
  if (form.type === 0) {
    form.unitPrice = 2.50
  } else if (form.type === 1) {
    form.fixedAmount = 200.00
  } else if (form.type === 2 || form.type === 4) {
    addTier()
  } else if (form.type === 3) {
    form.unitPrice = 3.50
  }
  
  // 自动生成计费方式名称
  generateBillingMethodName()
}

const addTier = () => {
  form.tierConfig.push({
    start: 0,
    end: 0,
    price: 0
  })
}

const removeTier = (index: number) => {
  form.tierConfig.splice(index, 1)
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  form.id = undefined
  form.name = ''
  form.buildingTypeName = undefined
  form.type = 0
  form.unitPrice = undefined
  form.fixedAmount = undefined
  form.tierConfig = []
  form.description = ''
  form.status = 1
  form.sortOrder = 1
  form.remark = ''
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 构建提交数据
    const submitData = {
      ...form,
      // 字段名映射
      methodName: form.name, // 前端name字段映射到后端methodName
      methodType: form.type, // 前端type字段映射到后端methodType
      feeType: props.feeType,
      propertyCompanyId: props.selectedCompanyId,
      // 将tierConfig数组转换为JSON字符串
      tierConfig: form.tierConfig && form.tierConfig.length > 0 
        ? JSON.stringify(form.tierConfig) 
        : null
    }
    
    emit('confirm', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 监听编辑数据
watch(() => props.billingMethod, (newVal) => {
  if (newVal) {
    // 编辑模式，填充表单数据
    console.log('编辑模式，加载计费方式数据:', newVal)
    
    // 处理buildingTypeName字段，确保是字符串类型
    let buildingTypeName: string | undefined
    if (newVal.buildingTypeName) {
      if (Array.isArray(newVal.buildingTypeName)) {
        // 如果是数组，取第一个元素
        buildingTypeName = newVal.buildingTypeName[0] || undefined
        console.warn('buildingTypeName是数组，取第一个元素:', newVal.buildingTypeName)
      } else {
        // 如果是字符串，直接使用
        buildingTypeName = newVal.buildingTypeName
      }
    }
    
    // 确保计费类型是数字类型，添加更严格的类型检查
    let methodType = 0
    try {
      if (newVal.methodType !== undefined && newVal.methodType !== null) {
        const convertedType = Number(newVal.methodType)
        if (!isNaN(convertedType) && convertedType >= 0 && convertedType <= 4) {
          methodType = convertedType
        } else {
          console.warn('无效的methodType值:', newVal.methodType, '使用默认值0')
          methodType = 0
        }
      } else if (newVal.type !== undefined && newVal.type !== null) {
        const convertedType = Number(newVal.type)
        if (!isNaN(convertedType) && convertedType >= 0 && convertedType <= 4) {
          methodType = convertedType
        } else {
          console.warn('无效的type值:', newVal.type, '使用默认值0')
          methodType = 0
        }
      } else {
        console.warn('未找到有效的计费类型值，使用默认值0')
        methodType = 0
      }
    } catch (error) {
      console.error('转换计费类型时出错:', error, '使用默认值0')
      methodType = 0
    }
    
    // 处理数值字段，确保类型正确
    const formData = {
      id: newVal.id,
      name: newVal.methodName || newVal.name || '', // 支持两种字段名
      buildingTypeName: buildingTypeName,
      type: methodType, // 确保是数字类型
      unitPrice: newVal.unitPrice !== undefined && newVal.unitPrice !== null ? Number(newVal.unitPrice) : undefined,
      fixedAmount: newVal.fixedAmount !== undefined && newVal.fixedAmount !== null ? Number(newVal.fixedAmount) : undefined,
      // 解析tierConfig JSON字符串为数组
      tierConfig: (() => {
        try {
          if (newVal.tierConfig) {
            if (typeof newVal.tierConfig === 'string') {
              return JSON.parse(newVal.tierConfig)
            } else if (Array.isArray(newVal.tierConfig)) {
              return newVal.tierConfig
            }
          }
          return []
        } catch (error) {
          console.error('解析tierConfig失败:', error, '使用空数组')
          return []
        }
      })(),
      description: newVal.description || '',
      status: newVal.status !== undefined && newVal.status !== null ? Number(newVal.status) : 1,
      sortOrder: newVal.sortOrder !== undefined && newVal.sortOrder !== null ? Number(newVal.sortOrder) : 1,
      remark: newVal.remark || ''
    }
    
    console.log('设置表单数据:', formData)
    console.log('计费类型值:', formData.type, '类型:', typeof formData.type)
    console.log('原始methodType:', newVal.methodType, '原始type:', newVal.type)
    
    // 使用Object.assign更新表单数据
    Object.assign(form, formData)
    
    // 强制更新表单数据，确保响应式更新
    nextTick(() => {
      console.log('nextTick后表单数据:', form)
      console.log('nextTick后计费类型:', form.type, '类型:', typeof form.type)
      
      // 验证表单数据是否正确设置
      if (typeof form.type !== 'number' || isNaN(form.type)) {
        console.error('计费类型设置失败，当前值:', form.type, '类型:', typeof form.type)
        // 强制设置为默认值
        form.type = 0
      }
    })
    
    // 编辑模式下，确保建筑类型列表已加载（避免重复调用）
    if (props.selectedCompanyId && buildingTypeList.value.length === 0) {
      loadBuildingTypeList()
    }
  } else {
    // 新增模式，重置表单
    resetForm()
    handleTypeChange()
  }
}, { immediate: true })

// 监听费用类型变化
watch(() => props.feeType, () => {
  if (!props.billingMethod) {
    // 新增模式下，重新设置默认值
    handleTypeChange()
  }
})

// 监听物业公司ID变化，加载建筑类型列表
watch(() => props.selectedCompanyId, (newVal) => {
  if (newVal) {
    loadBuildingTypeList()
  } else {
    buildingTypeList.value = []
  }
}, { immediate: true })

// 监听对话框显示状态，当打开时加载建筑类型列表（仅在新增模式下）
watch(() => props.modelValue, (newVal) => {
  if (newVal && props.selectedCompanyId && !props.billingMethod) {
    // 仅在新增模式下加载建筑类型列表，编辑模式已在billingMethod监听器中处理
    loadBuildingTypeList()
  }
})
</script>

<style scoped>
.billing-method-form {
  padding: 20px 0;
}

.unit-text {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}

.help-text {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

.tier-config {
  width: 100%;
}

.tier-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #fafafa;
}

.tier-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.tier-title {
  font-weight: 600;
  color: #303133;
}

.dialog-footer {
  text-align: right;
}
</style>
